import React, { Component } from 'react'
import { Button, Input, Table, Checkbox, Pagination, Modal, message, InputNumber } from 'antd'
import { CopyToClipboard } from 'react-copy-to-clipboard'
import { inject, observer } from 'mobx-react/index'
import FileSaver from 'file-saver'

import request from '@/Utils/fecth'
import { address } from '@/Utils/apiConfig'
import Empty from '@/pages/Dashboard/common/Empty'
import { USER_INFO, Peer_Status } from '@/Utils/CONST'
import { checkPermission } from '@/components/AuthComponent/utils'

import './index.less'

const { leagueManagement: { getOrganization, getOrgNodes, invite, orgVoteSet }, common: { download }} = address

@inject('BreadCrumb')
@observer
class Organization extends Component {
  constructor(props) {
    super(props)
    const { match: { params: { id, name }}} = this.props
    this.state = {
      dataList: [], // 组织列表
      organizationType: [
        { id: 'peer', text: 'peer', checked: false },
        { id: 'orderer', text: 'orderer', checked: false },
      ],
      pageNo: 1,
      pageSize: 10,
      inviteVisible: false,
      inviteLink: '',
      loading: true,
      consortiumId: id,
      orgName: name,
      voteVisible: false,
      voteVal: '',
      searchValue: '',
    }
  }

  componentDidMount() {
    this.getAllData()
  }

  openVoteModal = () => {
    const { leagueInfo } = this.props
    this.setState({
      voteVisible: true,
      voteVal: parseInt(leagueInfo.vote_strategy || 0, 10),
    })
  }

  // 获取组织列表和节点列表
  getAllData = async() => {
    let _List = await this.getOrganizationFn()
    let dataList = await this.getPeersFn(_List)
    this.setState({
      dataList,
      loading: false,
    })
    this.totalData = dataList || []
  }

  // 获取组织列表
  getOrganizationFn = async() => {
    let _List = null
    const { consortiumId } = this.state
    await request().get(getOrganization.format({ consortiumId })).then(res => {
      switch (res.status) {
      case 200:
        _List = res.data
        break
      default:
        message.error('请求失败')
        break
      }
    })
    return _List
  }

  // 获取组织下节点列表
  getPeersFn = async(_List) => {
    if (!(_List && _List.length)) return
    let result = await Promise.all(_List.map(async(item) => {
      const _id = item.id
      let obj = Object.assign({}, item)
      let peersArr = await this.getNodes(_id)
      obj['peersArr'] = peersArr
      return obj
    }))
    return result
  }

  getNodes = async(_id) => {
    let peersArr = null
    await request().get(getOrgNodes.format({ organizationId: _id })).then(res => {
      switch (res.status) {
      case 200:
        peersArr = res.data
        break
      default:
        message.error('请求失败')
        break
      }
    })
    return peersArr
  }

  confirm = (confirm) => {
    confirm && confirm()
  }
  // 重置 重置为初始状态
  clear = (clear, flag) => {
    let data = this.state[flag]
    data.map(element => {
      element.checked = false
    })
    this.setState({
      [flag]: data,
    })
    clear()
  }

  // 筛选
  dropDownRender = (setSelectedKeys, clearFilters, confirm) => {
    return (
      <div>
        <div className="ant-dropdown-menu" >
          {
            this.state.organizationType.map((item, idx) => {
              return (
                <li className="ant-dropdown-menu-item" key={item.text}
                  style={{ background: item.checked ? '#E9F5FF' : '#fff' }}
                  onClick={() => this.setcheckFn(item, idx, 'organizationType', setSelectedKeys)}
                >
                  <Checkbox checked={item.checked}> <span style={{ color: '#171E2D' }}>{item.text}</span></Checkbox>
                </li>
              )
            })
          }
        </div>
        <div className="ant-table-filter-dropdown-btns">
          <span className="clear"
            onClick={() => this.clear(clearFilters, 'organizationType')}
          >
            重置</span>
          <span className="confirm"
            onClick={() => this.confirm(confirm)}
          >确定</span>

        </div>
      </div>
    )
  }

  changeTableFn = () => {
    this.setState({ loading: true })
    let { organizationType, pageNo, pageSize } = this.state
    let _list = [] // 筛选后数据
    let filterList = organizationType.filter(item => item.checked)
    if (filterList && filterList.length) {
      filterList = filterList.map(ele => ele.id)
    } else {
      this.setState({
        dataList: this.totalData,
      })
    }

    if (filterList.length) {
      this.totalData.map(item => {
        filterList.includes(item.type) && _list.push(item)
      })

      if (_list.length < pageNo * pageSize) {
        pageNo = Math.ceil(_list.length / this.state.pageSize) || 1
      }

      this.setState({
        pageNo,
      }, () => {
        this.setState({
          dataList: _list,
        })
      })
    }
    this.setState({ loading: false })
  }

  setcheckFn = (level, index, flag, setSelectedKeys) => {
    // level 当前点击的check项数据
    let data = this.state[flag]

    data[index].checked = !level.checked

    this.setState({
      [flag]: data,
    })
    setSelectedKeys(data.filter(item => { return item.checked === true }))
  }

  changePaginationFn = (pageNumber) => {
    this.setState({
      pageNo: pageNumber,
    })
  }

  onShowSizeChangeFn = (current, pageSize) => {
    let { pageNo, dataList } = this.state
    if (dataList.length < current * pageSize) {
      pageNo = Math.ceil(dataList.length / pageSize) || 1
    }
    this.setState({
      pageSize,
      pageNo,
    })
  }

  inviteOrgFn = () => {
    const { consortiumId, orgName } = this.state
    request().get(invite.format({ consortiumId })).then((res = {}) => {
      const { status, data = {}} = res
      if (status === 200) {
        const link = window.location.protocol + '//' + window.location.host + '/dashboard/fabric/invite'
        const userInfo = JSON.parse(localStorage.getItem(USER_INFO) || '{}')
        const user = userInfo && userInfo.username
        this.setState({
          inviteLink: link + '?eventId=' + data.eventId + '&user=' + user + '&_org=' + orgName + '&_id=' + consortiumId,
        }, () => {
          this.setState({
            inviteVisible: true,
          })
        })
      } else {
        message.error('操作失败')
      }
    })
  }

  setRowClassName = (record) => {
    const { rowId } = this.state
    if (record.id === rowId) {
      return 'clickRowStyle'
    } else {
      return 'clickNoRowStyle'
    }
  }

  // 渲染表格
  renderTable = () => {
    const { dataList, pageNo, pageSize, loading } = this.state
    // 子表格
    const expandedRowRender = (record, index) => {
      const data = record.peersArr
      const columnsSub = [
        { title: '节点名称', dataIndex: 'name', key: 'name' },
        { title: '节点域名', dataIndex: 'domain', key: 'domain' },
        {
          title: '证书域名',
          dataIndex: 'cert_domain',
          key: 'cert_domain',
          render: (v, record) => {
            const detail = dataList[index] || {}
            return detail && detail.domain && record.domain && `${record.domain.split('.').join('-')}.${detail.domain.split('.').join('-')}.svc.cluster.local`
          },
        },
        { title: '访问地址', dataIndex: 'address', key: 'address', width: '25%', render: (v, record) => `grpcs://${record.node_domain}${record.node_port ? ':' + record.node_port : ''}` },
        {
          title: '所属通道',
          dataIndex: 'channels',
          key: 'channels',
          width: '15%',
          render: (text) =>
            <span>{text && text.length ? text.toString() : '-'}</span>,
        },
        {
          title: '状态',
          dataIndex: 'status',
          key: 'status',
          className: 'status',
          render: (text) => {
            const item = Peer_Status.find(v => v.id === text) || {}
            return <span className={item.className}>{item.text || '--'}</span>
          },
        },
      ]
      return <Table
        className="common-table-child"
        columns={columnsSub}
        rowKey={record => record.id}
        dataSource={data}
        pagination={false}

        rowClassName={this.setRowClassName}
      />
    }

    const columns = [
      { title: '组织名', dataIndex: 'display_name', key: 'display_name', render: (text) => <span>{text || '无'}</span> },
      {
        title: 'MSPID',
        dataIndex: 'MSPID',
        render: (text, record) => <span>{record.name + 'MSP'}</span>,
      },
      {
        title: '节点数', key: 'peersArr',
        render: (text, record) =>
          <span>{(record.peersArr && record.peersArr.length) || 0}</span>,

      },
      { title: '所属ID', dataIndex: 'userName', key: 'userName' },
      {
        title: '组织类型',
        dataIndex: 'type',
        key: 'type',
        width: 132,
        filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => {
          return this.dropDownRender(setSelectedKeys, clearFilters, confirm)
        },
      },
      {
        title: '操作',
        width: '100',
        dataIndex: 'tlsca',
        render: (text, record) => <span className="common-operation" style={{ cursor: 'pointer' }} onClick={() => this.downloadFn(record.tlsca)}>下载TLSCA证书</span>,
      },
    ]
    return (
      <div className="organization-table common">
        <Table
          pagination={false}
          className={dataList && dataList.length ? '' : 'empty-list'}
          onChange={this.changeTableFn}
          getPopupContainer={node => {
            if (node) {
              return node.parentNode
            }
            return document.body
          }}
          columns={columns}
          rowKey={record => record.id}
          expandedRowRender={expandedRowRender}
          locale={{
            emptyText: <div />,
          }}
          loading={loading}
          rowClassName={this.setRowClassName}
          dataSource={dataList ? dataList.slice((this.state.pageNo - 1) * this.state.pageSize, this.state.pageNo * this.state.pageSize) : []}
        />
        {
          dataList && dataList.length ? null : <Empty />
        }
        <div className="pagination-box">
          {/* 总数*/}
          {
            dataList && dataList.length
              ? <Pagination
                current={pageNo}
                pageSize={pageSize}
                total={dataList.length}
                showSizeChanger
                showQuickJumper
                onShowSizeChange={this.onShowSizeChangeFn}
                onChange={this.changePaginationFn} />
              : null
          }
        </div>
      </div>

    )
  }

  handleCancel = () => {
    this.setState({
      inviteVisible: false,
    })
  }

  voteHandleCancel = () => {
    this.setState({
      voteVisible: false,
    })
  }

  // 投票策略弹窗的确认事件
  voteHandleOk = () => {
    const { voteVal, consortiumId } = this.state
    request().post(orgVoteSet.format({ consortiumId }), {
      strategy: voteVal.toString(),
    }).then(res => {
      if (res.status === 200) {
        message.success('设置成功')
      }
      // 关闭弹窗
      this.voteHandleCancel()
      const { getLeagueInfo } = this.props
      getLeagueInfo && getLeagueInfo()
    })
  }

  changeVote = (value) => {
    this.setState({
      voteVal: value,
    })
  }

  // 申请添加组织
  goApply = () => {
    this.props.history.push({
      pathname: `/dashboard/fabric/${this.state.consortiumId}/${this.state.orgName.toString()}/apply`,
    })
  }

  // 组织名称模糊查询
  queryName = () => {
    const { searchValue } = this.state
    if (searchValue) {
      const dataList = this.totalData
      const newList = dataList.filter(item => item.display_name.indexOf(searchValue) >= 0)
      this.setState({
        dataList: newList,
      })
    } else {
      this.setState({
        dataList: this.totalData,
      })
    }
  }

  downloadFn = (value) => {
    if (!value) {
      message.error('获取组织TLSCA证书失败')
      return
    }
    const blob = new Blob([value], { type: 'application/octet-stream' })
    FileSaver.saveAs(blob, 'TLSCA.pem')
  }

  downloadSdk = async() => {
    Modal.confirm({
      content: '是否确认下载国密SDK到本地?',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        const filename = 'guomi-sdk-2.0.3.zip'
        request().get(download, {
          responseType: 'blob',
          params: {
            filename: encodeURIComponent(filename),
          },
        }).then(res => {
          const status = res.status
          if (status === 200) {
            FileSaver.saveAs(res.data, filename)
          }
        })
      },
    })
  }

  render() {
    const { inviteVisible, inviteLink, loading, voteVisible, voteVal } = this.state
    // const { leagueInfo } = this.props
    return (
      <div id="organization-page" className="organization-page common">
        <div className="organization-opreate">
          <div className="btn">
            {
              checkPermission('fabric-org-apply') &&
            <Button type="primary" disabled={loading} onClick={this.goApply}>申请添加组织</Button>
            }
            {/* <Button type="primary" onClick={this.inviteOrgFn} disabled={loading}>邀请组织</Button> */}
            {/* {
              !!leagueInfo.isGuomi &&
              <Button type="primary" onClick={this.downloadSdk} style={{ marginBottom: 24, marginLeft: 8 }}>国密SDK下载</Button>
            } */}
            {
              checkPermission('fabric-org-vote') &&
            <Button disabled={loading} onClick={this.openVoteModal}>投票管理</Button>
            }
          </div>
          <div className="common-search">
            <input ref={b => this.input = b}
              className="search-input"
              placeholder="请输入组织名"
              type="text"
              onKeyDown={(event) => {
                event.keyCode === 13 && this.queryName()
              }}
              value={this.state.searchValue}
              autoComplete="off"
              onChange={(e) => this.setState({ searchValue: e.target.value })}
            />
            <div className="search-btn">
              <img src={require('@/images/org/search.svg')} alt="" onClick={() => this.queryName()} />
            </div>
          </div>
        </div>
        {
          this.renderTable()
        }
        <Modal
          className="common-normal-modal invite-modal"
          getContainer={() => document.getElementById('organization-page')}
          title="邀请组织"
          visible={inviteVisible}
          footer={null}
          onCancel={this.handleCancel}
          style={{ width: 508, height: 220, top: '50%', marginTop: '-110px' }}
        >
          <p className="title">将链接发送给邀请对象，对方点击链接接受邀请后，即可加入组织</p>
          <div className="link">
            <Input value={inviteLink} readOnly />
            <CopyToClipboard text={inviteLink}
              onCopy={() => message.success('复制成功')}>
              <Button className="com-normal-btn com-btn-primary">复制链接</Button>
            </CopyToClipboard>

          </div>
          <p className="tip">链接有效期为7天</p>
        </Modal>
        <Modal
          className="common-small-modal vote-modal"
          getContainer={() => document.getElementById('organization-page')}
          title="设置投票策略"
          visible={voteVisible}
          width={455}
          onOk={this.voteHandleOk}
          onCancel={this.voteHandleCancel}
          centered
          style={{ width: 455, height: 200 }}
        >
          <div className="vote-content">
            <label>投票策略</label>
            <InputNumber value={voteVal} onChange={this.changeVote} max={100} min={0} />
            <span className="percent">%</span>
          </div>
        </Modal>
      </div>
    )
  }
}

export default Organization
